; System Interrupt Routines
SysInterrupt:
	push af
	push bc
	push de
	push hl
	push ix
	push iy
	exx
	ex af, af'
	push af
	push bc
	push de
	push hl
	xor a
	ld (RAMEnd),a
	ld (RAMEnd-1),a
#ifdef USBModel
	jp HandleUSBEvents
#endif
ResumeInterrupt:
	in a, (04h)
	bit 0, a
		jr nz, HandleON
	bit 1, a
		jr nz, HandleTimer1
	bit 2, a
		jr nz, HandleTimer2
	bit 4, a
		jr nz, HandleLink
	jr InterruptDone
HandleON:
	in a, (03h)
	res 0, a
	out (03h), a
	set 0, a
	out (03h), a
	; ON interrupt
	ld a,(OverlayEnabled)
	if(ENABLED)
		jp z,HandleOverlay
	jr InterruptDone
HandleTimer1:
	in a, (03h)
	res 1, a
	out (03h), a
	set 1, a
	out (03h), a
	; Timer one interrupt
	jr InterruptDone
HandleTimer2:
	in a, (03h)
	res 2, a
	out (03h), a
	set 2, a
	out (03h), a
	; Timer two interrupt
	jp Tasker
HandleLink:
	in a, (03h)
	res 4, a
	out (03h), a
	set 4, a
	out (03h), a
	; Link interrupt
InterruptDone:
	pop hl
	pop de
	pop bc
	pop af
	ex af, af'
	exx
	pop iy
	pop ix
	pop hl
	pop de
	pop bc
	pop af
	ei
	ret
#ifdef USBModel
HandleUSBEvents:
	in a, (55h) ; Read USB status
	bit 0, a
	jr z, UnknownUSBEvent
	bit 2, a
	jr z, USBLineInterrupt
	bit 4, a
	jp z, USBProtocolInterrupt
	jp ResumeInterrupt
UnknownUSBEvent:
	xor a
	out (5Bh), a ; Unknown event, WikiTI claims you should zero port 5B to acknowledge
	jp ResumeInterrupt
USBLineInterrupt:
	in a, (56h)
	ld c, a
	cpl ; xor 0FFh
	ld b, a
	in a, (57h)
	ld d, a
	and b
	out (57h), a
	ld a, d
	out (57h), a	; Ack the interrupt without doing anything special
	jp ResumeInterrupt
USBProtocolInterrupt:
	in a, (86h)
	ld c, a
	in a, (84h)
	ld b, a
	in a, (85h)
	in a, (83h)
	in a, (82h) ; Just ack and leave, and hope that it doesn't get angry
	jp ResumeInterrupt
#endif
